package com.firexxx.study.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.Properties;

/**
 * @Author yztao2@iflytek.com
 * @Description 读取配置文件配置项工具类
 * @Date 11:02 2020/11/3
 *
 **/
public class ConfigUtil {

    private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
    private static Properties props = new Properties();

    static {
        try {
            String configFile = ConfigUtil.class.getClassLoader().getResource("application.properties").getFile();
            props.load(new InputStreamReader(new FileInputStream(configFile), "UTF-8"));
            getXmlVersion(props);
        } catch (Exception e) {
            logger.error("msg=初始化配置文件失败", e);
        }
    }

    private static void getXmlVersion(Properties props) throws ParserConfigurationException, IOException, SAXException {
        String configFile = ConfigUtil.class.getClassLoader().getResource("application.properties").getFile();
        File baseDir = new File(configFile).getParentFile().getParentFile();
        String[] versionFile = new File(baseDir, "version").list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.startsWith("version-") && name.endsWith(".txt")) {
                    return true;
                }
                return false;
            }
        });
        if (versionFile!=null && versionFile.length > 0) {
            props.put("version", versionFile[0]);
        } else {
            props.put("version", "未知");
        }
    }

    public static void update(Properties p) {
        props = p;
        logger.info("infomsg=ConfigUtil properties update success");
    }

    public static int getInt(String key, int defaultValue) {
        String value = props.getProperty(key);
        if ("".equals(value) || value == null) {
            return defaultValue;
        }
        try {

            return Integer.parseInt(value);

        } catch (Exception ex) {
            return defaultValue;
        }
    }

    public static String getValue(String key) {
        return props.getProperty(key);
    }

    public static String getValue(String key, String defValue) {
        String ret = props.getProperty(key);
        if (ret == null || ret.isEmpty() || ret.equals("")) {
            return defValue;
        }
        return ret;
    }

}
